<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use app\models\Orderinfo;
use app\models\PlanBillItem;

class OrderController extends Controller
{
	public function actionIndex()
	{	
		$query = new \yii\db\Query();

		$displayAll = Yii::$app->request->get("displayAll",0);

		if($displayAll == 1){
			$list = $query->select("*")->from("JXC_ORDERINFO")->orderBy("ORDERINFOID DESC")->all();
		}else{
			$list = $query->select("*")->from("JXC_ORDERINFO")->orderBy("ORDERINFOID DESC")->limit(DEFAULT_LIMIT)->all();
		}

		return $this->render("index",['list' => $list]);
	}

	private function generateQueryString($fieldName){
		if (empty($fieldName))
			return "";
		$getFieldNameRequest = $_GET[$fieldName];
		if (empty($getFieldNameRequest))
			return "";
		else
			return $fieldName." like '%".$getFieldNameRequest."%'";
	}

	public function actionSearch()
	{	
		$productname = $_GET['productname'];
		$drawingno = $_GET['drawingno'];
		$plannum = $_GET['plannum'];

		$query = new \yii\db\Query();
		
		$query->select("*")->from("JXC_ORDERINFO");

		$queryString = $this->generateQueryString("ordernum");
		if(!empty($queryString)){
			$query->andWhere($queryString);
		}

		$queryString = $this->generateQueryString("orderunit");
		if(!empty($queryString)){
			$query->andWhere($queryString);
		}

		$queryString = $this->generateQueryString("receivingunit");
		if(!empty($queryString)){
			$query->andWhere($queryString);
		}

		if($productname != "" || $drawingno != "")
		{
			$orderList = Orderinfo::getIdFromItem($productname,$drawingno);
			if(!empty($orderList))
				$query->andWhere("orderinfoid in (".$orderList.")");
			else
				$query->andWhere("orderinfoid = 0");
		}

		if($plannum != "")
		{
			$orderList = PlanBillItem::getOrderidByPlannum($plannum);
			if(!empty($orderList))
				$query->andWhere("orderinfoid in (".$orderList.")");
			else
				$query->andWhere("orderinfoid = 0");
		}

		$list = $query->all();

		return $this->render("index",['list' => $list]);
	}

	public function actionItem()
	{
		$orderinfoid = $_GET['id'];

		$query = new \yii\db\Query();
		
		$list = $query->select("*")
			->from("JXC_ORDERITEM")
			->where("ORDERINFOID = ".$orderinfoid)
			->all();

		$sumPrice = 0;
		$sumCount = 0;
		foreach ($list as  $value) {
			$sumPrice += $value['PRICE'];
			$sumCount += $value['COUNT'];
		}

		return $this->render("item",['list' => $list,'sumPrice'=>$sumPrice,'sumCount'=>$sumCount]);
	}
}